﻿using Godot;
using System;
using System.IO;
using System.Diagnostics;

public partial class Logger : Node
{
    private const string LogPath = "user://logs/";
    private static readonly string LogFile = $"Log_{DateTime.Now:yyyyMMdd}.log";
    private static Logger _instance; 
    public static Logger Instance => _instance ??= new Logger();

    public override void _EnterTree()
    {
        base._EnterTree();
        if (_instance == null) return;
        _instance = this;
        InitLogSystem();
    }

    public enum LogLevel {
        Info,
        Warning,
        Error
    }

    public override void _Ready()
    {
        InitLogSystem();
        GD.Print("Logger system initialized");
    }

    private void InitLogSystem()
    {
        // 创建日志目录
        if (!DirAccess.DirExistsAbsolute(LogPath))
        {
            DirAccess.MakeDirRecursiveAbsolute(LogPath);
        }
    }
    //region:静态类
    /// <summary>
    /// 消息
    /// </summary>
    /// <param name="msg"></param>
    public static void SMsg(string msg)
    {
        SWriteLog(LogLevel.Info, msg);
    }
    /// <summary>
    /// 警告
    /// </summary>
    /// <param name="msg"></param>
    public static void SWarn(string msg)
    {
        SWriteLog(LogLevel.Warning, msg);
    }
    /// <summary>
    /// 错误
    /// </summary>
    /// <param name="msg"></param>
    public static void SError(string msg)
    {
        SWriteLog(LogLevel.Error, msg);
    }
    
    //endregion

    public void Msg(string message)
    {
        WriteLog(LogLevel.Info, message);
    }

    public void Warn(string message)
    {
        WriteLog(LogLevel.Warning, message);
    }

    public void Error(string message)
    {
        WriteLog(LogLevel.Error, message);
        GD.PushError(message); // 同时输出到Godot错误控制台
    }

    private static void WriteLog(LogLevel level, string message)
    {
        // 调整堆栈跟踪深度为3，跳过Logger包装方法
        var callerFrame = new StackTrace(true).GetFrame(2); 
        
        // 添加null安全判断
        var callerInfo = callerFrame != null ? 
            $"{Path.GetFileName(callerFrame.GetFileName())}:{callerFrame.GetMethod()?.Name}:{callerFrame.GetFileLineNumber()}" 
            : "UnknownSource";
        
        var logEntry = $"[{GetCurrentTime()}] [{level}] [{callerInfo}] {message}";
        
        // 控制台输出带颜色标记
        GD.PrintRich(GetColoredLog(level, logEntry));
        
        // 文件记录（保留原有实现）
        using var file = Godot.FileAccess.Open(Path.Combine(LogPath, LogFile), Godot.FileAccess.ModeFlags.WriteRead);
        file.SeekEnd();
        file.StoreLine(logEntry);
    }
    
    /// <summary>
    /// 静态方法
    /// </summary>
    /// <param name="level"></param>
    /// <param name="message"></param>
    private static void SWriteLog(LogLevel level, string message)
    {
        // 调整堆栈跟踪深度为3，跳过Logger包装方法
        var callerFrame = new StackTrace(true).GetFrame(2); 
        
        // 添加null安全判断
        var callerInfo = callerFrame != null ? 
            $"{Path.GetFileName(callerFrame.GetFileName())}:{callerFrame.GetMethod()?.Name}:{callerFrame.GetFileLineNumber()}" 
            : "UnknownSource";
        
        var logEntry = $"[{GetCurrentTime()}] [{level}] [{callerInfo}] {message}";
        
        // 控制台输出带颜色标记
        GD.PrintRich(GetColoredLog(level, logEntry));
        
        // 文件记录（保留原有实现）
        using var file = Godot.FileAccess.Open(Path.Combine(LogPath, LogFile), Godot.FileAccess.ModeFlags.WriteRead);
        file.SeekEnd();
        file.StoreLine(logEntry);
    }
    private static string GetColoredLog(LogLevel level, string message)
    {
        return level switch
        {
            LogLevel.Info => $"[color=#89CFF0]{message}[/color]",    // 浅蓝色
            LogLevel.Warning => $"[color=#FFD700]{message}[/color]", // 金色
            LogLevel.Error => $"[color=#FF5733]{message}[/color]",   // 橙色
            _ => message
        };
    }

    private static string GetCurrentTime()
    {
        return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
    }
}
